//
//  RouteDetailViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/23.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "RouteDetailViewController.h"
#import "HMSegmentedControl.h"
#import "UIImageView+WebCache.h"

#import "CommonService.h"
#import "TourismDetailsEntity.h"

#import "OrderEnsureViewController.h"
#import "LoginViewController.h"
#import "NSDate+WQCalendarLogic.h"
#import "RouteDetailModel.h"
#define k 7
#define imageHeight 200
@interface RouteDetailViewController ()<UIScrollViewDelegate,UIWebViewDelegate>
{
    CalendarHomeViewController *chvc;
}
@property (nonatomic, strong) IBOutlet UIImageView *imageViewProduce;
@property (nonatomic, strong) IBOutlet UILabel *labelTitle;
@property (nonatomic, strong) IBOutlet UILabel *labelSubTitle;
@property (nonatomic, strong) IBOutlet UILabel *labelPrice;
@property (nonatomic, strong) IBOutlet UILabel *labelProPrice;
@property (nonatomic, strong) IBOutlet UIWebView *webViewContent;
@property (nonatomic, strong) IBOutlet UILabel *labelTraffic;
@property (nonatomic, strong) IBOutlet UILabel *labelDesc;
@property (nonatomic, strong) TourismDetailsEntity *tDetailEntity;

@property (weak, nonatomic) IBOutlet UIView *viewNavigation;
@property (strong, nonatomic) IBOutlet UIView *routeView;
@property (weak, nonatomic) IBOutlet UIScrollView *routeScrollView;
@property (weak, nonatomic) IBOutlet UIButton * btnShare;
@property (weak, nonatomic) IBOutlet UIButton * btnBack;
@property (weak, nonatomic) IBOutlet UIView *viewSegment;
@property (strong,nonatomic) HMSegmentedControl *segmentedControl2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *img_height;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *routeview_height;
@property (nonatomic, assign) CGFloat addlength;
@property (weak, nonatomic) IBOutlet UILabel *phone_label;

@property (weak, nonatomic) IBOutlet UIView *wraperView;


@end

#define K_title  @"线路详情"

#define K_tripTip  @"行程简介"
#define K_feeTip  @"费用说明"
#define K_bookTip  @"预订须知"




@implementation RouteDetailViewController
@synthesize imageViewProduce, labelPrice, labelProPrice, labelSubTitle;
@synthesize labelTitle, webViewContent, labelDesc, labelTraffic;
@synthesize routeEntity, tDetailEntity;
@synthesize routeView,routeScrollView,viewSegment,viewNavigation,segmentedControl2,wraperView;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = K_title;
    
    routeView.frame = CGRectMake(0, 0, self.view.bounds.size.width,768);
    [self.routeScrollView addSubview:routeView];
    routeScrollView.contentSize = CGSizeMake(self.view.frame.size.width,768);
    routeScrollView.delegate = self;
    webViewContent.delegate = self;
    webViewContent.scrollView.scrollEnabled = NO;
    viewNavigation.alpha = 0.0;
//    [imageViewProduce setValue:imageViewProduce.frame.origin.x forKey:@"frame.origin.x"];
//    [imageViewProduce addObserver:self forKeyPath:@"frame.origin.x" options:NSKeyValueObservingOptionNew context:NULL];
    self.addlength = imageHeight/320.f*SCREEN_WIDTH - imageHeight;
    self.img_height.constant = imageHeight/320.f*SCREEN_WIDTH;
    self.routeview_height.constant = 330 + self.addlength;

    
    if (is_IOS_7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    segmentedControl2 = [[HMSegmentedControl alloc] initWithSectionTitles:@[K_tripTip, K_feeTip, K_bookTip]];
    [segmentedControl2 setIndexChangeBlock:^(NSUInteger index) {
        if (index == 0) {
            NSString * urlString = tDetailEntity.in_characteristic;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            
            [webViewContent loadHTMLString:str4 baseURL:nil];
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_characteristic]];
//            [webViewContent loadRequest:request];
        } else if (index == 1) {
            NSString * urlString = tDetailEntity.in_tariff_description;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            [webViewContent loadHTMLString:str4 baseURL:nil];
//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_tariff_description]];
//            [webViewContent loadRequest:request];
        } else if (index == 2) {
            NSString * urlString = tDetailEntity.in_reservation_information;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData *data = [NSData dataWithContentsOfURL:url];
            NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSString * str2 = K_websiteStyleStr;
            NSString * str3 = [str2 stringByAppendingString:str];
            NSString *str4 = [str3 stringByAppendingString:@"</div>"];
            [webViewContent loadHTMLString:str4 baseURL:nil];

//            NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_reservation_information]];
//            [webViewContent loadRequest:request];
        }
        NSLog(@"Selected index %lu (via block)", (unsigned long)index);
    }];
    
    [segmentedControl2 setSelectionIndicatorHeight:4.0f];
    [segmentedControl2 setBackgroundColor:[UIColor whiteColor]];
    [segmentedControl2 setTextColor:[UIColor darkGrayColor]];
    [segmentedControl2 setSelectionIndicatorColor:[UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1]];
    [segmentedControl2 setSelectionIndicatorMode:HMSelectionIndicatorFillsSegment];
    [segmentedControl2 setSegmentEdgeInset:UIEdgeInsetsMake(0, 6, 0, 6)];
    [segmentedControl2 setCenter:CGPointMake(160, 120)];
    [segmentedControl2 setTag:2];
    segmentedControl2.frame = CGRectMake(k, self.routeview_height.constant + 10, SCREEN_WIDTH-2*k, 40);
    [self.view addSubview:segmentedControl2];
    
    [self getRouteDetailInfo];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    NSLog(@"Selected index %li (via UIControlEventValueChanged)", (long)segmentedControl.selectedIndex);
}

- (void) getRouteDetailInfo {
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           routeEntity.t_id, @"t_id",nil];
    
    [service getNetWorkData:param
                       Path:TRAVEL_DETAIL
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSDictionary *dic_data = [dic objectForKey:@"row"];
                      
                      tDetailEntity = [[TourismDetailsEntity alloc] init];
                      tDetailEntity = [tDetailEntity initWithAttributes:dic_data];
                      
                      dispatch_async(dispatch_get_main_queue(), ^{
                          [self initViewController];
                      });
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      
                  }];
}

- (void) initViewController {
    if ([tDetailEntity.can_sale isEqualToString:@"0"])
    {
        self.buyBtn.hidden = YES;
    }
    else
    {
        self.buyBtn.hidden = NO;
    }
    [self.imageViewProduce sd_setImageWithURL:[NSURL URLWithString:tDetailEntity.t_image_url]];
    
    self.labelTitle.text = tDetailEntity.t_name;
    self.labelPrice.text = [NSString stringWithFormat:@"%@元", tDetailEntity.t_price] ;
    
    NSString *old_price = [NSString stringWithFormat:@"原价：%@元", tDetailEntity.t_old_price];
    self.labelProPrice.text = old_price;
    
    self.labelTraffic.text = tDetailEntity.t_vehicle;
    
    NSMutableString *string = [[NSMutableString alloc]init];
    for (RouteDetailModel * detailModel in tDetailEntity.t_departure_date_list) {
        [string appendString:detailModel.dep_time];
        [string appendString:@"  "];

    }
    self.labelDesc.text = string;
    NSUInteger length = [old_price length];
    
    NSString * urlString = tDetailEntity.in_characteristic;
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSString * str2 = K_websiteStyleStr;
    NSString * str3 = [str2 stringByAppendingString:str];
    NSString *str4 = [str3 stringByAppendingString:@"</div>"];
    [webViewContent loadHTMLString:str4 baseURL:nil];
    
//    NSString *HTMLData = tDetailEntity.in_reference;
//    [self.webViewContent loadHTMLString:HTMLData
//                                baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle]  bundlePath]]];
//    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:tDetailEntity.in_characteristic]];
//    [webViewContent loadRequest:request];
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:old_price];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    [self.labelProPrice setAttributedText:attri];
    
    if (tDetailEntity.a_tel == nil || tDetailEntity.a_tel.length == 0)
    {
        self.phone_label.text = NoTelNumber;
    }
    else
    {
        self.phone_label.text = tDetailEntity.a_tel;
    }
}

- (IBAction)shareAction:(id)sender {
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    NSArray* imageArray = [[NSArray alloc] initWithObjects:[imageViewProduce image], nil];
    
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:tDetailEntity.t_name
                                Content:tDetailEntity.t_price];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y >0) {
        _btnBack.hidden = YES;
        //_btnSave.hidden = YES;
        _btnShare.hidden = YES;
        DebugLog(@"%f", scrollView.contentOffset.y);
        
        viewNavigation.alpha = 1.0*(scrollView.contentOffset.y/(imageViewProduce.bounds.size.height-viewNavigation.bounds.size.height));
       
        [self.view bringSubviewToFront:viewNavigation];
    } else {
        _btnBack.hidden = NO;
        //_btnSave.hidden = NO;
        _btnShare.hidden = NO;
        
        viewNavigation.alpha = 0.0;
    }
//    segmentedControl2.frame = CGRectMake(k, self.routeview_height.constant + 10, self.view.bounds.size.width-2*k, 40);
    
    if (scrollView.contentOffset.y > self.routeview_height.constant + 10 - 62) {

        segmentedControl2.frame =CGRectMake(k, 61, self.view.bounds.size.width-2*k, 40);
    }
    else{

        segmentedControl2.frame = CGRectMake(k, wraperView.bounds.size.height+10-scrollView.contentOffset.y, self.view.bounds.size.width-2*k, 40);
    }

    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    
    CGFloat documentHeight = [[webViewContent stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"content\").offsetHeight;"] floatValue];
    CGRect frame = webViewContent.frame;
    if (documentHeight < 424) {
        frame.size.height = 510;
        webViewContent.frame = frame;
        
        CGRect frame2 = routeScrollView.frame;
        frame2.size.height = 766;
        routeScrollView.contentSize = frame2.size;
        
        DebugLog(@"frame3.size.height = %f", frame2.size.height);
    } else {
        frame.size.height = documentHeight+43;
        webViewContent.frame = frame;
        
        
        DebugLog(@"documentHeight=%f, %f", documentHeight, webViewContent.scrollView.contentSize.height);
        
        CGRect frame2 = routeScrollView.frame;
        
        frame2.size.height = documentHeight+350 +43;
        routeScrollView.contentSize = frame2.size;
        
        DebugLog(@"frame3.size.height = %f", frame2.size.height);
    }
    
    
}

-(IBAction)buyItRightNow:(id)sender{
    
//    ALERT_ERR_MSG(@"此功能正在开发中");
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
//    OrderEnsureViewController *vc = [[OrderEnsureViewController alloc] init];
//    vc.tDetailsEntity = tDetailEntity;
//    vc.userEntity = userEntity;
    chvc = [[CalendarHomeViewController alloc]init];
    chvc.calendartitle = @"出行日期";
    chvc.tourismDetailsEntity = self.tDetailEntity;
    chvc.saler_phone = self.saler_phone;
    NSDate   *startDate = [NSDate date];
    RouteDetailModel *endDateModel = [self.tDetailEntity.t_departure_date_list lastObject];
    NSString *endDate = endDateModel.dep_time;
    int days = [NSDate getDaysFrom:startDate To:[NSDate dateFromYMDString:endDate]];
    [chvc setAirPlaneToDay:days+1 ToDateforString:nil withDateArray:self.tDetailEntity.t_departure_date_list];//初始化方法
    [self.navigationController pushViewController:chvc animated:YES];
}

- (IBAction)doCallPhone:(id)sender {
    
    if (tDetailEntity.a_tel == nil || tDetailEntity.a_tel.length == 0) {
        ALERT_ERR_MSG(NoTelNumber);
        return;
    }
    
    NSString *number = tDetailEntity.a_tel;// 此处读入电话号码
    // NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number为号码字符串 如果使用这个方法 结束电话之后会进入联系人列表
    NSString *num = [[NSString alloc] initWithFormat:@"telprompt://%@",number]; //而这个方法则打电话前先弹框  是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //拨号
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RouteDetailViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"RouteDetailViewController"];
}
@end



